<template>
  <div class="container">
    <el-card class="agents-card">
      <!-- 页面头部 -->
      <el-row type="flex" justify="space-between" class="header">
        <el-col><el-button type="primary" @click="addBtn">添加经纪</el-button></el-col>
        <el-col>
          <el-input placeholder="请输入关键字" v-model="searchKey">
            <el-button slot="append" icon="el-icon-search" @click="searchAgents"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- 经纪人表格 -->
      <el-table :data="agentsList" border style="width: 100%; margin-top: 30px">
        <el-table-column prop="image" label="图片" width="122">
          <template #default="{ row }">
            <img v-imgError="defaultAvatar" :src="row.image" alt="" class="avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="180"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
        <el-table-column prop="desc" label="介绍"> </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div>
              <el-button type="primary" @click="editBtn(row.id)">编辑</el-button>
              <el-button type="danger" @click="deleteAgent(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" justify="center" class="footer">
        <el-pagination layout="prev, pager, next" :current-page.sync="currentPage" :page-size="pageSize" :total="total" @current-change="CurrentPageChange"> </el-pagination>
      </el-row>
    </el-card>
    <!-- 添加/编辑经纪人弹窗 -->
    <el-dialog :title="agentTitle" :visible.sync="showDialog" width="50%" :before-close="handleClose">
      <!-- 表单信息 -->
      <el-form ref="agentForm" :model="agentsInfo" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="agentsInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="agentsInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="agentsInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="agentsInfo.address"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" rows="4" v-model="agentsInfo.desc"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <upload-img ref="upload-img"></upload-img>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAgentsList, getAgentCount, addAgent, delAgent, getAgentById, editAgent } from '@/api/agents'
import userHeader from '@/assets/bigUserHeader.png'
export default {
  data() {
    return {
      /** 搜索关键字 */
      searchKey: '',
      /** 经纪人列表 */
      agentsList: [],
      defaultAvatar: userHeader,

      /** 当前页 */
      currentPage: 1,
      /** 每页显示条数 */
      pageSize: 3,
      /** 总条数 */
      total: 10,
      /** 显示隐藏添加经纪人弹窗 */
      showDialog: false,
      /** 经纪人弹窗表单 */
      agentTitle: '',
      /** 新增经纪人表单信息 */
      agentsInfo: {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''
      },
      /** 表单校验 */
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '电子邮箱格式不正确', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /[0-9]+/, message: '电话号码应为纯数字(0-9)', trigger: 'blur' }
        ],
        desc: [{ required: true, message: '请输入描述信息', trigger: 'blur' }]
      }
    }
  },
  async created() {
    await this.getList()
  },
  methods: {
    /** 获取经纪人列表数据, 渲染列表及分页器 */
    async getList() {
      let start = (this.currentPage - 1) * this.pageSize
      // console.log(start)
      let res = await getAgentsList({ _limit: this.pageSize, _start: start, name_contains: this.searchKey })
      // console.log(res)
      this.agentsList = res.data
      res = await getAgentCount(this.searchKey)
      // console.log(res.data)
      this.total = res.data
    },
    /** 当前页发生改变 */
    CurrentPageChange() {
      this.getList()
    },
    /** 点击搜索经纪人 */
    searchAgents() {
      this.getList()
    },
    /** 点击添加经纪按钮 */
    addBtn() {
      this.agentTitle = '新增经纪'
      this.showDialog = true
    },
    /** 点击编辑经纪按钮, 数据回流，显示弹窗 */
    async editBtn(id) {
      this.agentTitle = '编辑经纪'
      let res = await getAgentById(id)
      console.log(res.data)
      this.agentsInfo = res.data
      // 因为此刻弹窗还没有显示，无法拿到弹窗里面的 upload-img 组件，所以要用 nextTick
      this.$nextTick(() => {
        this.$refs['upload-img'].imageUrl = res.data.image
      })
      this.showDialog = true
    },
    /** 点击删除经纪, 确认删除后, 刷新页面, 当删除当前页最后一条数据，并且当前页不是第一页时，返回上一页 */
    async deleteAgent(id) {
      this.$confirm('确认删除改经纪？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delAgent(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          if (this.agentsList.length === 1 && this.currentPage > 1) {
            this.currentPage--
          }
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /** 提交表单，通过校验，头像上传完成，新增经纪信息，关闭弹窗 */
    submit() {
      this.$refs['agentForm'].validate(async valid => {
        if (valid) {
          // 编辑经纪
          if (this.agentsInfo.id) {
            let progress = this.$refs['upload-img'].percentage
            if (progress === 100 || progress === 0) {
              await editAgent(this.agentsInfo)
              this.getList()
              this.handleClose()
            }
          }
          // 新增经纪
          else {
            let progress = this.$refs['upload-img'].percentage
            if (progress === 100 || progress === 0) {
              this.agentsInfo.image = this.$refs['upload-img'].imageUrl
              // 如果没有上传图片，给一个可校验通过的默认图片链接
              if (progress === 0) {
                this.agentsInfo.image = 'https://upload-bbs.miyoushe.com/upload/2022/12/16/273950678/4ef7bbb8a8a3e82a46def1c963817df0_9083921191925804707.png'
              }
              await addAgent(this.agentsInfo)
              this.getList()
              this.handleClose()
            } else {
              this.$message({
                type: 'warning',
                message: '等待图片上传中，请稍后再提交'
              })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /** 关闭弹窗,重置表单 */
    handleClose() {
      this.showDialog = false
      this.agentsInfo = {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''
      }
      this.$refs['agentForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
// .container {
//   width: 100%;
// }
.agents-card {
  // display: block;
  margin: 20px;
  .header {
    padding-bottom: 40px;
    border-bottom: 1px solid #e9e6e9;
  }
  .footer {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e9e6e9;
  }
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: contain;
}
</style>
